<template>
   
    <div ref="chartRef" style="width: 100%; height: 100%;"></div>
    
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from 'vue';
import * as echarts from 'echarts/core';
import { PieChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

// 按需引入 echarts 模块
echarts.use([
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  LabelLayout,
  CanvasRenderer
]);

// 定义 props 的类型
interface ChartOption {
  tooltip: {
    trigger: string;
    formatter?: (params: any) => string;
  };
  legend: {
    show: boolean;
  };
  series: Array<{
    type: string;
    radius: string[];
    center: string[];
    data: Array<{
      value: number;
      name: string;
      itemStyle?: {
        color: string;
      };
      label?: {
        show: boolean;
      };
    }>;
    label?: {
      show: boolean;
      position: string;
      formatter: () => string;
      rich?: Record<string, any>;
    };
    emphasis?: {
      disabled: boolean;
    };
  }>;
}

const props = defineProps<{
  option: ChartOption;
}>();

const chartRef = ref<HTMLElement | null>(null);
let chart: echarts.ECharts | null = null;

// 使用防抖函数优化 resize
let resizeTimer: number | null = null;
const handleResize = () => {
  if (resizeTimer) clearTimeout(resizeTimer);
  resizeTimer = setTimeout(() => {
    chart?.resize();
  }, 100);
};

onMounted(() => {
  if (chartRef.value) {
    chart = echarts.init(chartRef.value);
    chart.setOption(props.option);
    window.addEventListener('resize', handleResize);
  }
});

// 优化 watch，使用防抖
let updateTimer: number | null = null;
watch(() => props.option, (newOption) => {
  if (updateTimer) clearTimeout(updateTimer);
  updateTimer = setTimeout(() => {
    if (chart) {
      chart.setOption(newOption, true);
    }
  }, 100);
}, { deep: true });

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  chart?.dispose();
  if (resizeTimer) clearTimeout(resizeTimer);
  if (updateTimer) clearTimeout(updateTimer);
});

// 确保导出为默认导出
defineOptions({
  name: 'UserPie'
})
</script>

<style lang="scss" scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px;  /* 确保最小高度 */
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
